/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.client.gwt.core.ui;

import java.util.ArrayList;

import com.gadglet.client.gwt.GadgetConfig;
import com.gadglet.client.gwt.GadgetNativeUtils;
import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.FormItemListBox;
import com.gadglet.client.gwt.ui.FormItemProfilePhoto;
import com.gadglet.client.gwt.ui.FormItemTextBox;
import com.gadglet.client.gwt.ui.VerticalFormPanel;
import com.gadglet.client.gwt.ui.VerticalFormPanel.FromItemsArray;
import com.gadglet.params.GadgetType;
import com.gadglet.params.ProfPrivacyStatus;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqErrorTypes;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.impl.PreferencesUtil;
import com.google.gwt.gadgets.client.osapi.Callback;
import com.google.gwt.gadgets.client.osapi.OsapiError;
import com.google.gwt.gadgets.client.osapi.OsapiRequest;
import com.google.gwt.gadgets.client.osapi.people.GetPersonRequestBuilder;
import com.google.gwt.gadgets.client.osapi.people.PeopleService;
import com.google.gwt.gadgets.client.osapi.people.Person;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;


/**
 * UI class used by the user to define some profile properties
 *
 */

public class ProfileEditDialogPanel {

	DebugDialogBox debug = DebugDialogBox.getErrorNotifier();

	final GadgletQuery viewProfileQry = new GadgletQuery();

	final GadgletQuery saveProfileQry = new GadgletQuery();

	final ViewProfileRequest viewProfileRequest = new ViewProfileRequest(
			viewProfileQry);

	final SaveProfileRequest saveProfileRequest = new SaveProfileRequest(
			saveProfileQry);

	private static ProfileEditDialogPanel profileRegistration;
	private boolean isProfileExists = false;
	private DialogBox dialogBox;
	private HTML detailsHTML;
	final VerticalFormPanel form = new VerticalFormPanel();

	protected final PreferencesUtil prefs = PreferencesUtil.nativeInitPrefs();

	public static ProfileEditDialogPanel getProfileRegistration() {
		if (profileRegistration == null) {
			profileRegistration = new ProfileEditDialogPanel();
		}
		return profileRegistration;
	}

	boolean isProfileExists() {
		return isProfileExists;
	}

	void setProfileExists(boolean isProfileExists) {
		this.isProfileExists = isProfileExists;
	}

	private ProfileEditDialogPanel() {
		dialogBox = new DialogBox();
		dialogBox.setAnimationEnabled(true);

		detailsHTML = new HTML();
		detailsHTML.setVisible(true);

		form.setTitlesWidth("100px");
		form.setControlWidth("200px");
		final Button saveButton = new Button(prefs.getMsg("gadgetLabelSave"));
		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {

				String nickName = form.getFormItem(
						ProfileFields.PROFILE_NICKNAME.getParamName())
						.getFieldValue();

				if (nickName != null && !nickName.trim().isEmpty()) {

					ArrayList<FromItemsArray> allFields = null;

					if (isProfileExists())
						saveProfileQry
								.setRequestAction(ReqActionTypes.UPDATE_PROFILE);
					else
						saveProfileQry
								.setRequestAction(ReqActionTypes.ADD_PROFILE);

					allFields = form.getFromValues();

					saveProfileQry.clearParamList();

					try {
						for (int i = 0; i < allFields.size(); i++){
							saveProfileQry.addParam(allFields.get(i).getName(),
									allFields.get(i).getValue());
							
						}
							
					} catch (Exception e) {
						debug.showError(105, e.getMessage());

					}

					saveProfileRequest.makeRequest();

				}
			}
		});

		final Button closeButton = new Button(prefs.getMsg("gadgetLabelClose"));
		closeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});

		FormItemProfilePhoto myPhoto = new FormItemProfilePhoto(
				ProfileFields.PROFILE_THUMBNAILURL.getParamName(),
				"gadgetLabelProfilePhoto", null,
				prefs.getMsg("gadgetLabelShare"));
		myPhoto.getFieldEntry().setVisible(false);
		form.add(myPhoto);

		form.add(new FormItemTextBox(ProfileFields.PROFILE_NICKNAME
				.getParamName(), "gadgetLabelProfileNickName", ""));

		// add title for bizlet
		if (GadgetConfig.getGadgetConfig().getGadgetType()
				.equals(GadgetType.BIZLET))
			form.add(new FormItemTextBox(ProfileFields.PROFILE_TITLE
					.getParamName(), "gadgetLabelTitle", ""));

		// add Privacy for minglets
		if (GadgetConfig.getGadgetConfig().getGadgetType()
				.equals(GadgetType.MINGLET)) {
			FormItemListBox status = new FormItemListBox(
					ProfileFields.PROFILE_PRIVACY.getParamName(),
					"gadgetLabelProfilePrivacyStatus");

			// status private is disabled
			// status.getFieldControl().addItem(prefs.getMsg("gadgetLabelProfilePrivacyPrivate"),ProfPrivacyStatus.PRIVATE.getPrivacyStatus());

			status.getFieldControl().addItem(
					prefs.getMsg("gadgetLabelProfilePrivacyProtected"),
					ProfPrivacyStatus.PROTECTED.getPrivacyStatus());
			status.getFieldControl().addItem(
					prefs.getMsg("gadgetLabelProfilePrivacyPublic"),
					ProfPrivacyStatus.PUBLIC.getPrivacyStatus());
			form.add(status);

		}

		VerticalPanel dialogVPanel = new VerticalPanel();

		dialogVPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

		dialogVPanel.setSize(GadgetNativeUtils.getGadgetWidth() / 2 + "px",
				GadgetNativeUtils.getGadgetHeight() / 2 + "px");

		ScrollPanel panel = new ScrollPanel(detailsHTML);

		FlowPanel buttons = new FlowPanel();

		buttons.add(closeButton);
		buttons.add(saveButton);

		dialogVPanel.add(panel);
		dialogVPanel.add(form);
		dialogVPanel.add(buttons);
		dialogBox.setWidget(dialogVPanel);

	}

	public void editProfile() {

		try {
			

			PeopleService peopleService = PeopleService.getInstance();

			GetPersonRequestBuilder builder = peopleService
					.newGetViewerRequestBuilder();
			builder.setFields("thumbnailUrl", "name");

			OsapiRequest<Person> viewer = builder.build();

			Callback<Person> callback = new Callback<Person>() {
				@Override
				public void onFail(OsapiError error) {
					
					if(error!=null)
					debug.showError(111, "OsapiError error:"+error.getMessage());

				}

				@Override
				public void onSuccess(Person viewer) {
					
					if (viewer.getThumbnailUrl() != null) {

						form.getFormItem(
								ProfileFields.PROFILE_THUMBNAILURL
										.getParamName()).getFieldEntry()
								.setVisible(true);
						Image photo = (Image) form.getFormItem(
								ProfileFields.PROFILE_THUMBNAILURL
										.getParamName()).getFieldControl();
						photo.setUrl(viewer.getThumbnailUrl());

					}

				}
			};
			viewer.execute(callback);
		} catch (Exception e) {
			
			debug.showError(333, "exception:"+e.getMessage());

		}

		viewProfileQry.setRequestAction(ReqActionTypes.GET_PROFILE);
		viewProfileRequest.makeRequest();

	}

	public class ViewProfileRequest extends GadgletRequest {
		ViewProfileRequest(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse jResponse) {

			if (jResponse.isSuccessful()) {
				dialogBox.setText(prefs.getMsg("gadgetLabelEdit") + " "
						+ prefs.getMsg("gadgetLabelProfile"));
				setProfileExists(true);
				if (jResponse.getItem(0) != null)
					form.setFormValues(jResponse.getItem(0));

			} else if (jResponse.getError().equals(
					ReqErrorTypes.PROFILE_DOESNT_EXISTS.getErrorMessage())) {

				dialogBox.setText(prefs.getMsg("gadgetLabelRegister"));
				detailsHTML.setHTML(prefs
						.getMsg("gadgetMsgProfileRegistration"));

				setProfileExists(false);

			} else
				debug.showError(101, jResponse.getError());

			if (GadgetUtils.isCanvasView())
				GadgetUtils.dialogBoxTop(dialogBox);
			else
				dialogBox.center();

		}
	}

	public class SaveProfileRequest extends GadgletRequest {
		SaveProfileRequest(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			dialogBox.hide();
			
			if (!jResponse.isSuccessful()) {
			
				debug.showError(101, jResponse.getError());
			}

		}
	}

}
